﻿using mds.BaseFrameModel;
using mds.NoSqlDatabase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace mds.LoginSecurityService
{
    internal class LoginCacheProvider
    {
        private static LoginCacheProvider _instance = new LoginCacheProvider();
        private RedisProvider _reidsClient;
        public static LoginCacheProvider Instance
        {
            get { return _instance; }           
        }
        private LoginCacheProvider()
        {
            _reidsClient = new RedisProvider();
        }
        public OperationResult<bool> SaveSession(Guid sessionId, long userId)
        {
            var connection = LoginItemService.Instance.GetConnection("Master");
             var connectionSlave = LoginItemService.Instance.GetConnection("slave");
             var sessionIds = _reidsClient.Get<List<String>>(userId.ToString(), connectionSlave.Host, connectionSlave.Port);
             sessionIds.Add(sessionId.ToString());
             _reidsClient.Save<long, List<String>>(userId, sessionIds, connection.Host, connection.Port);
            return _reidsClient.Save<Guid, long>(sessionId, userId, connection.Host, connection.Port);
        }
        public OperationResult<bool> ClearSession(Guid sessionId)
        {
            var connection = LoginItemService.Instance.GetConnection("Master");
           return _reidsClient.Delete(sessionId.ToString(), connection.Host, connection.Port);
        }

        public long GetUserId(Guid sessionId)
        {
            var connection = LoginItemService.Instance.GetConnection("Slave");
             return _reidsClient.Get<long>(sessionId.ToString(), connection.Host, connection.Port);
        }

        public void ClearSessions(long userId)
        {
            var connection = LoginItemService.Instance.GetConnection("Master");
            var list=_reidsClient.Get<List<String>>(userId.ToString(), connection.Host, connection.Port);
            _reidsClient.Deletes(list, connection.Host, connection.Port);
        }
    }
}
